package com.ruoyi.bean.service;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.Constants;
import com.ruoyi.common.result.Result;
import com.ruoyi.common.util.IpUtils;
import com.ruoyi.common.util.MD5Util;
import com.ruoyi.domain.vo.LoginVo;
import com.ruoyi.web.domain.vo.entity.SysUser;
import com.ruoyi.web.domain.vo.model.LoginUser;
import io.github.stylesmile.annotation.AutoWired;
import io.github.stylesmile.annotation.Service;
import io.github.stylesmile.jedis.JedisTemplate;
import io.github.stylesmile.server.Request;

/**
 * @author cy
 */
@Service
public class LoginService {
    @AutoWired
    JedisTemplate jedisTemplate;

    public Result<LoginVo> login(String username, String password, String code, String uuid, Request request) {

        SysUser user = this.findUserByUserName(username);
        if (null == user) {
        }
        if (!MD5Util.calculateMD5(password).equals(user.getPassword())) {
        }

        String strJson = JSON.toJSONString(user);
//        String accessToken = MD5Util.calculateMD5(strJson + System.currentTimeMillis() + IPUtil.getClientIP(request));
        String accessToken = MD5Util.calculateMD5(strJson + System.currentTimeMillis() + IpUtils.getIpAddr(request));
        LoginUser loginUser = LoginUser.builder()
                .loginTime(System.currentTimeMillis())
                .userId(user.getUserId())
                .user(user)
                .token(accessToken)
                .build();
        jedisTemplate.setSerializeDataEx(
                String.format(Constants.LOGIN_USER_KEY + ":" + user.getUserId(), accessToken),
                loginUser, 7200);
        LoginVo loginVo = new LoginVo();
        loginVo.setAccessToken(accessToken);
        loginVo.setExpireIn(3600000L);
        return Result.ok(loginVo);
    }

    public SysUser findUserByUserName(String username) {
        LambdaQueryWrapper<SysUser> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(SysUser::getUserName, username);
//        return this.getOne(queryWrapper);
//        return sysUserMapper.selectOne(queryWrapper);
        return null;
    }
}
